package com.kkshop.util;

import org.acegisecurity.context.SecurityContextHolder;
import org.apache.log4j.Logger;

import com.kkshop.model.AbstractUser;
import com.kkshop.model.security.User;
import com.kkshop.model.util.security.ExtendedUser;
import com.kkshop.service.PersistenceService;

public class UserUtils {
    
    private static final Logger log = Logger.getLogger(UserUtils.class);
    
    private PersistenceService persistenceService;
    
    public boolean userExists(String username) {
        try {
            return persistenceService.find(User.class, username) != null;
        } catch (Exception e) {
            log.error("Could find user", e);
            return false;
        }
    }
    
    public String getCurrentUser() {
        Object principal = (SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        if(principal instanceof ExtendedUser) {
            return ((ExtendedUser) principal).getUsername();
        } else if(principal instanceof AbstractUser) {
            return ((AbstractUser) principal).getUser().getUsername();
        } else {
            return (String) principal;
        }
    }

    public PersistenceService getPersistenceService() {
        return persistenceService;
    }

    public void setPersistenceService(PersistenceService persistenceService) {
        this.persistenceService = persistenceService;
    }
}
